import * as React from "react";
import { Table, Spin, Button, Modal, Space, Typography, Switch } from "antd";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import IconFont from "../../../../../../assets/ICON";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import {
  getPricePageData,
  deletePriceData,
  updateStatus,
} from "../../../ServeApi";
import moment from "moment";
import "./index.less";
import PriceFileModal from "../PriceFileModal";

const { Text } = Typography;
export interface PriceFileTableProps {
  ConditionAttr: ConditionAttrData;
}
interface ConditionAttrData {
  priceType: string;
  isEnable: string;
}
export interface PriceFileTableState {
  loading: boolean;
  pageSize: number;
  pageIndex: number;
  total: number;
  visible: boolean;
  initValue: any;
}

class PriceFileTable extends React.Component<
  PriceFileTableProps,
  PriceFileTableState
> {
  state = {
    loading: false,
    pageSize: 20,
    pageIndex: 1,
    total: 0,
    visible: false,
    initValue: null,
  };
  private columns: columnsDataCLass[] = [
    {
      title: "价格类型",
      dataIndex: "priceType",
      key: "priceType",
      render: (text: string) => {
        let str: string = "";
        switch (text) {
          case "0":
            str = "单价";
            break;
          case "1":
            str = "分时价";
            break;
          default:
            str = "测试类型";
            break;
        }
        return <>{str}</>;
      },
    },
    {
      title: "价格名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "价格",
      dataIndex: "unitPrice",
      key: "unitPrice",
    },
    {
      title: "是否可用",
      dataIndex: "isEnable",
      key: "isEnable",
      render: (text, record) => {
        let b: boolean = text === "0" ? true : false;
        return (
          <Switch
            checked={b}
            onChange={(checked) => {
              this.onChangeState(checked, record);
            }}
          />
        );
      },
    },
    {
      title: "创建人",
      dataIndex: "createBy",
      key: "createBy",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text: string) => {
        return moment(text).format("YYYY-MM-DD");
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              <span
                onClick={() => {
                  this.onDelete(record);
                }}
                style={{ cursor: "pointer" }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  private dataSouce: any[] = [];
  render() {
    return (
      <div className="PriceFileTable">
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.setState({ visible: true });
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table
              columns={this.columns}
              dataSource={this.dataSouce}
              pagination={{
                pageSize: this.state.pageSize,
                current: this.state.pageIndex,
                total: this.state.total,
                onChange: (page: number) => {
                  this.setState({ pageIndex: page });
                },
              }}
            ></Table>
          </Spin>
          <PriceFileModal
            visible={this.state.visible}
            onOk={(data: boolean) => {
              this.hanldOk(data);
            }}
            onCancel={(data: boolean) => {
              this.hanldCancel(data);
            }}
            defaultValue={this.state.initValue}
          ></PriceFileModal>
        </div>
      </div>
    );
  }
  /**钩子函数 */
  componentWillMount() {
    this.getPricePageData();
  }
  //参数生成
  setPream() {
    let { pageIndex, pageSize } = this.state;
    let pream = {
      pageIndex,
      pageSize,
      queryData: this.props.ConditionAttr,
    };
    return pream;
  }
  /**数据请求 */
  //请求价格分页数据
  async getPricePageData() {
    let _this = this;
    try {
      let pream: any = this.setPream();
      this.setState({ loading: true });
      let res: any = await getPricePageData(
        JSON.stringify(pream)
      ).catch((err) => {});
      let json: AjaxData = res;
      if (json.success) {
        this.dataSouce = json.data.records;
        this.setState({ total: json.data.total });
        this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: `请求出错,请检查设备链接和网络情况。`,
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
    }
  }
  //删除价格数据
  async deletePriceData(id: string) {
    let pream = { id };
    try {
      let res: any = await deletePriceData(JSON.stringify(pream));
      let json: AjaxData = res;
      if (json.success) {
        this.getPricePageData();
      } else {
        Modal.error({ title: json.message });
      }
    } catch (error) {}
  }
  async onChangeState(checked: boolean, record: any) {
    let pream: ChangeStatePream = {
      isEnable: checked ? "0" : "1",
      id: record.id,
    };
    try {
      let res: any = await updateStatus(JSON.stringify(pream));
      let json: AjaxData = res;
      if (json.success) {
        this.getPricePageData();
      } else {
        Modal.error({ title: json.message });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
      });
    }
  }
  /**操作 */
  //编辑价格分项
  onEdit(recors: any) {
    this.setState({ initValue: recors, visible: true });
  }
  //删除价格
  onDelete(recors: any) {
    let _this = this;
    Modal.confirm({
      title: "确认删除这条信息么?",
      icon: <ExclamationCircleOutlined />,
      content: "请选择",
      onOk() {
        _this.deletePriceData(recors.id);
      },
      onCancel() {
        // console.log("Cancel");
      },
    });
  }
  //确认
  hanldOk(bn: boolean) {
    this.setState({ visible: bn, initValue: null });
    this.getPricePageData();
  }
  //取消
  hanldCancel(bn: boolean) {
    this.setState({ visible: bn, initValue: null });
  }
}
interface ChangeStatePream {
  id: string;
  isEnable: string;
}
export default PriceFileTable;
